package com.thwcompany.service.impl;
import com.thwcompany.pojo.Mail;
import com.thwcompany.service.PublisherModeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageBuilder;
import org.springframework.amqp.core.MessageDeliveryMode;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

//发布-订阅模式
@Slf4j
@Service
@SuppressWarnings("all")
public class PublisherModeServiceImpl implements PublisherModeService {
	@Autowired
	RabbitTemplate rabbitTemplate;

	@Override
	public void publishMail(Mail mail) {

		rabbitTemplate.convertAndSend("fanout", null, mail);
	}

	@Override
	public void senddirectMail(Mail mail, String routingkey) {
		String messageId= UUID.randomUUID().toString();
		//构建消息体
		Message msg= MessageBuilder.withBody(String.valueOf(mail).getBytes())
				.setMessageId(messageId)// 设置消息唯一标识
				.setContentType(MessageProperties.CONTENT_TYPE_TEXT_PLAIN)//消息类型
				.setDeliveryMode(MessageDeliveryMode.PERSISTENT)//设置消息持久化
				.setContentEncoding("UTF-8")//消息编码
				.setExpiration("10000")//这条消息的过期时间，单位毫秒，过期后消息会被删除
				.setPriority(5)//优先级
				.setUserId("root")
				.build();
		CorrelationData correlationData = new CorrelationData(messageId);
		rabbitTemplate.convertAndSend("direct", routingkey, msg,correlationData);
		log.info("exchange交换机= {} ,路由键= {} ，要路由的消息message:{} ,messageId= {}","direct",routingkey, mail.toString(),msg.getMessageProperties().getMessageId());
		//rabbitTemplate.convertAndSend("direct", routingkey, mail);
	}

	@Override
	public void sendtopicMail(Mail mail, String routingkey) {

		rabbitTemplate.convertAndSend("mytopic", routingkey, mail);
	}

	
	
}
